package kanolaag;

import java.util.ArrayList;
import java.util.List;

import lpt.*;

public class Kanolaag extends Thread {

	private SoftwareLpt lpt;
	private List<Trit> buffer = new ArrayList<Trit>();
	private boolean isClosed = false;

	public Kanolaag() {
		super("Kanolaag");
		// lpt = new SoftwareLpt();
	}

	public void run() {
		while (!isClosed) {
			if (!buffer.isEmpty()) {
				Trit trit = buffer.get(buffer.size() - 1);
				buffer.remove(buffer.size() - 1);
				while(trit.hasNext()) {
					lpt.writeLPT(trit.next());
					try {
						Thread.sleep(50);
					} catch (InterruptedException e) {
						System.err.println("Fail in run() in Kanolaag");
						System.exit(-1);
					}
				}
			}
		}
	}

	public void send(byte bytes[]) {
		int i = 0;
		for (i = 0; i < bytes.length - 2; i += 3) {
			int b1 = ((int) bytes[i] & 0xff) << 16;
			int b2 = ((int) bytes[i + 1] & 0xff) << 8;
			int b3 = ((int) bytes[i + 2] & 0xff);
			int b = b1 + b2 + b3;

			Trit trit = new Trit(b);
			buffer.add(trit);
		}
	}

	public byte[] receive() {
		byte result[] = new byte[3];
		int i = 0;
		byte prev = -1;
		while (i < 4) {
			byte b = lpt.readLPT();
			if (b != prev) {
				result[i] = b;
				i++;
			}
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				System.err.println("Fail in receive()");
				System.exit(-1);
			}
		}
		
		return result;
	}
	
	public void close() {
		isClosed = true;
	}
}
